package cc.smarnet.caihou.phone.fragment;


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import cc.smarnet.caihou.App;
import cc.smarnet.caihou.IPConfig;
import cc.smarnet.caihou.LoginActivity;
import cc.smarnet.caihou.PrintTagHuaActivity;
import cc.smarnet.caihou.R;
import cc.smarnet.caihou.entity.FlowerBoxesDetal;
import cc.smarnet.caihou.entity.TFlowerTagIn2;
import cc.smarnet.caihou.util.BarChartUtils;
import okhttp3.Call;

import android.content.SharedPreferences;

public class StatisticsFragment extends Fragment {
    private View view;
    BarChart barChart1;
    BarChart barChart2;

    private List<Entry> netLineList = new ArrayList<>();

    private List<BarEntry> netBarList = new ArrayList<>();
    private List<String> netDateList = new ArrayList<>();

    private List<BarEntry> netBarList2 = new ArrayList<>();
    private List<String> netDateList2 = new ArrayList<>();

    private int xLableCount = 7;
    private int xRangeMaximum = xLableCount - 1;
    private int xLableCount2 = 7;
    private int xRangeMaximum2 = xLableCount - 1;

    private PieChart mPieChart;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_statistics, container, false);
        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        barChart1 = view.findViewById(R.id.barChart1);
        Description description = new Description();

        description.setText("单位：KG");
        description.setTextSize(12f);
        description.setTextColor(Color.BLUE);
        barChart1.setDescription(description);
        barChart1.setLeft(2);

        barChart2 = view.findViewById(R.id.barChart2);
        barChart2.setDescription(description);
        barChart2.setLeft(2);


        //柱状图初始化
        BarChartUtils.initChart(barChart1, true, true, true);
        BarChartUtils.initChart(barChart2, true, true, true);

        //设置数据
        setData();


        //饼状图

        mPieChart = view.findViewById(R.id.mPieChart);

        mPieChart.setUsePercentValues(true);//设置value是否用显示百分数,默认为false

        mPieChart.getDescription().setEnabled(false);//设置描述

        mPieChart.setExtraOffsets(5, 10, 5, 5);//设置饼状图距离上下左右的偏移量

        mPieChart.setDragDecelerationFrictionCoef(0.95f);//设置阻尼系数,范围在[0,1]之间,越小饼状图转动越困难

//设置中间文件

        mPieChart.setCenterText(generateCenterSpannableText());

// mPieChart.setCenterText("总学生数:100人");

        mPieChart.setDrawHoleEnabled(true);//是否绘制饼状图中间的圆

        mPieChart.setHoleColor(Color.WHITE);//饼状图中间的圆的绘制颜色

        mPieChart.setTransparentCircleColor(Color.WHITE);//设置圆环的颜色

        mPieChart.setTransparentCircleAlpha(110);//设置圆环的透明度[0,255]

        mPieChart.setHoleRadius(58f);//饼状图中间的圆的半径大小

        mPieChart.setTransparentCircleRadius(61f);//设置圆环的半径值

        mPieChart.setDrawCenterText(true);//是否绘制中间的文字

        mPieChart.setRotationAngle(0);//设置饼状图旋转的角度

// 触摸旋转

        mPieChart.setRotationEnabled(true);
        ;//设置饼状图是否可以旋转(默认为true)

        mPieChart.setHighlightPerTapEnabled(true);//设置旋转的时候点中的tab是否高亮(默认为true)

//变化监听

//        mPieChart.setOnChartValueSelectedListener(this);


//        initData();
        getAccount2();
    }


    /**
     * 获取默认查询的时间(当前时间的前day天)
     */
    public static String formatDatas(int day) {
        Date dNow = new Date(); // 当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); // 得到日历
        calendar.setTime(dNow);// 把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -day); // 设置为前三天
        dBefore = calendar.getTime(); // 得到前三天的时间
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd"); // 设置时间格式
        String defaultStartDate = sdf.format(dBefore); // 格式化
        return defaultStartDate;

    }

    /**
     * new Entry(x,y) x: 折线图中数据值的位置索引 y: 具体数据值
     */

    private void setData() {
//        netLineList.clear();
        netBarList.clear();
        netDateList.clear();
        netBarList2.clear();
        netDateList2.clear();
       /* String s;
        SimpleDateFormat dateFormat1 = new SimpleDateFormat(
                "MM-dd");
        Calendar c = Calendar.getInstance();
        String currentDate = dateFormat1.format(c.getTime());
        netDateList.add(currentDate);
        for (int i = 1; i < 7; i++) {
            s = formatDatas(i);
            netDateList.add(s);
        }
        Collections.reverse(netDateList);*/

        getAccount();

/*
        float[] lineFloat = {11, 22, 16, 17, 16, 16, 12};
        for (int i = 0; i < netDateList.size(); i++) {
//            netLineList.add(new Entry((float) i, (float) Math.random() * 80));
//            netLineList.add(new Entry((float) i, lineFloat[i]));
            netBarList.add(new BarEntry((float) i, lineFloat[i]));
        }*/

//        xLableCount = (netDateList.size() + 3) > 7 ? 7 : (netDateList.size() + 3);
//        xRangeMaximum = xLableCount + 1;
//
//
//        BarChartUtils.setXAxis(barChart1, xLableCount, netDateList.size(), xRangeMaximum);
//        BarChartUtils.notifyDataSetChanged(barChart1, netBarList, netDateList, "#38A45A");
//
//
//        BarChartUtils.setXAxis(barChart2, xLableCount, netDateList.size(), xRangeMaximum);
//        BarChartUtils.notifyDataSetChanged(barChart2, netBarList, netDateList, "#A4384C");


        //无数据
        //LineChartUtils.NotShowNoDataText(mBinding.lineChart);
//        BarChartUtils.NotShowNoDataText(barChart1);

    }

    public void getAccount() {

        SharedPreferences sp = App.getContext().getSharedPreferences("userInfo", App.getContext().MODE_PRIVATE);
        String token = sp.getString("token", null);
        String url = IPConfig.baseUrl + "/flower/flowerCost/getIn7";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .readTimeOut(100000)
                .connTimeOut(100000)
                .writeTimeOut(100000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(App.getContext(), "Token失效，请重新登录" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(App.getContext(), LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONObject jsonObject = JSON.parseObject(result);


                            JSONArray list = jsonObject.getJSONArray("list");
                            JSONArray list2 = jsonObject.getJSONArray("list2");

                            for (int i = 0; i < list.size(); i++) {
                                JSONObject json = list.getJSONObject(i);
                                netDateList.add(json.getString("variety"));
                                netBarList.add(new BarEntry((float) i, Float.valueOf(json.getString("tagNum"))));
                            }
                            if (list.size() <= 0) {
                                BarChartUtils.NotShowNoDataText(barChart1);
                            } else {
                                xLableCount = (netDateList.size() + 3) > 7 ? 7 : (netDateList.size() + 3);
                                xRangeMaximum = xLableCount - 1;
                                BarChartUtils.setXAxis(barChart1, xLableCount, netDateList.size(), xRangeMaximum);
                                BarChartUtils.notifyDataSetChanged(barChart1, netBarList, netDateList, "#38A45A");
                            }


                            for (int i = 0; i < list2.size(); i++) {
                                JSONObject json = list2.getJSONObject(i);
                                netDateList2.add(json.getString("variety"));
                                netBarList2.add(new BarEntry((float) i, Float.valueOf(json.getString("number"))));
                            }
                            if (list2.size() <= 0) {
                                BarChartUtils.NotShowNoDataText(barChart2);
                            } else {
                                xLableCount2 = (netDateList2.size() + 3) > 7 ? 7 : (netDateList2.size() + 3);
                                xRangeMaximum2 = xLableCount2 - 1;
                                BarChartUtils.setXAxis(barChart2, xLableCount2, netDateList2.size(), xRangeMaximum2);
                                BarChartUtils.notifyDataSetChanged(barChart2, netBarList2, netDateList2, "#A4384C");
                            }
                        } else {
                            BarChartUtils.NotShowNoDataText(barChart1);
                            BarChartUtils.NotShowNoDataText(barChart2);
                        }
                    }
                });
    }

    private void setDataFor30() {
        netLineList.clear();
        netBarList.clear();
        netDateList.clear();
        String s2;
        SimpleDateFormat dateFormat2 = new SimpleDateFormat(
                "MM-dd");
        Calendar c2 = Calendar.getInstance();
        String currentDate2 = dateFormat2.format(c2.getTime());
        netDateList.add(currentDate2);
        for (int i = 1; i < 30; i++) {
            s2 = formatDatas(i);
            netDateList.add(s2);
        }
        Collections.reverse(netDateList);


        float[] lineFloat = {14, 15, 16, 17, 16, 16, 12, 14, 15, 16, 17, 16, 16, 12, 14, 15, 16, 17, 16, 16, 12, 14, 15, 16, 17, 16, 16, 12, 14, 15};
        for (int i = 0; i < netDateList.size(); i++) {

//            netLineList.add(new Entry((float) i, (float) Math.random() * 80));
//            netBarList.add(new BarEntry((float) i, (float) Math.random() * 80));
            netLineList.add(new Entry((float) i, lineFloat[i]));
            netBarList.add(new BarEntry((float) i, lineFloat[i]));

        }

        xLableCount = (netDateList.size() + 3) > 7 ? 7 : (netDateList.size() + 3);
        xRangeMaximum = xLableCount - 1;


        BarChartUtils.setXAxis(barChart1, xLableCount, netDateList.size(), xRangeMaximum);
        BarChartUtils.notifyDataSetChanged(barChart1, netBarList, netDateList, "#38A45A32");

        //无数据
        //LineChartUtils.NotShowNoDataText(mBinding.lineChart);
        //BarChartUtils.NotShowNoDataText(mBinding.barChart);

    }


    public void getAccount2() {

        SharedPreferences sp = App.getContext().getSharedPreferences("userInfo", App.getContext().MODE_PRIVATE);
        String token = sp.getString("token", null);
        String url = IPConfig.baseUrl + "/flower/flowerCost/getInVers";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .readTimeOut(100000)
                .connTimeOut(100000)
                .writeTimeOut(100000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(App.getContext(), "Token失效，请重新登录" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(App.getContext(), LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONObject jsonObject = JSON.parseObject(result);


                            JSONArray list = jsonObject.getJSONArray("list");

                            ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
                            for (int i = 0; i < list.size(); i++) {
                                JSONObject jsonObject1 = list.getJSONObject(i);
                                entries.add(new PieEntry(Float.valueOf(jsonObject1.getString("tagNum")), jsonObject1.getString("variety")));
                            }
                            initDataPie(entries);
                        }
                    }
                });
    }


    //饼图
    private void initDataPie(ArrayList<PieEntry> entries) {

//模拟数据
      /*  ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        entries.add(new PieEntry(60, "优秀"));
        entries.add(new PieEntry(20, "满分"));
        entries.add(new PieEntry(30, "及格"));
        entries.add(new PieEntry(15, "不及格"));*/

//设置数据

        setData(entries);
        mPieChart.animateY(1400, Easing.EaseInOutCubic);
//设置每个tab的显示位置
        Legend l = mPieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(true);
        l.setXEntrySpace(0f);
        l.setYEntrySpace(0f);//设置tab之间Y轴方向上的空白间距值
        l.setYOffset(0f);

// 输入标签样式
        mPieChart.setDrawEntryLabels(true);//设置是否绘制Label
        mPieChart.setEntryLabelColor(Color.WHITE);//设置绘制Label的颜色
        mPieChart.setEntryLabelTextSize(14f);//设置绘制Label的字体大小

    }

//设置中间文字

    private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("采收产品比例\n\n各产品百分比%");
//        SpannableString s = new SpannableString("产品比例\n\n设置属性控制文字样式");
        s.setSpan(new RelativeSizeSpan(1.7f), 0, 6, 0);

// s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
// s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
// s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
// s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
// s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);

        return s;

    }

//设置数据

    private void setData(ArrayList<PieEntry> entries) {

//        PieDataSet dataSet = new PieDataSet(entries, "产品比例颜色");
        PieDataSet dataSet = new PieDataSet(entries, "");
        dataSet.setSliceSpace(4f);
        dataSet.setSelectionShift(10f);

//数据和颜色

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(18f);
        data.setValueTextColor(Color.WHITE);
        mPieChart.setData(data);
        mPieChart.highlightValues(null);
//刷新
        mPieChart.invalidate();

    }


}
